<template>
  <div class="register-container">
    <div class="register-box">
      <div class="register-header">
        <div class="logo">
          <el-icon>
            <Notification />
          </el-icon>
        </div>

        <h2 class="register-title">创建账号</h2>
        <p class="register-subtitle">加入我们，开启全新体验</p>
      </div>


      <el-form ref="loginFormRef" :model="formData" :rules="rules" @keyup.enter="handleSubmit" class="register-form">
        <el-form-item prop="username">
          <el-input v-model="formData.username" size="large" placeholder="请输入用户名" prefix-icon="User" clearable />
        </el-form-item>
        <el-form-item prop="email">
          <el-input v-model="formData.email" size="large" placeholder="请输入邮箱" prefix-icon="Message" clearable />
        </el-form-item>
        <el-form-item prop="code">
          <el-input v-model="formData.code" size="large" type="text" placeholder="请输入验证码" prefix-icon="Lock" clearable>
            <template #append>
              <div class="code-btn">
                <el-button v-show="sendTime === 60" type="primary" size="small" @click="sendCode">发送验证码</el-button>
                <el-button v-show="sendTime < 60" type="primary" disabled size="small" @click="sendCode">
                  {{ sendTime }}
                </el-button>
              </div>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="formData.password" size="large" type="password" placeholder="请输入密码" prefix-icon="Lock"
            show-password clearable />
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input v-model="formData.confirmPassword" size="large" type="password" placeholder="请确认密码"
            prefix-icon="Lock" show-password clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="register-btn" :loading="loading" @click="handleSubmit">
            注册账号
          </el-button>
        </el-form-item>
      </el-form>

      <div class="login-link">
        已有账号？
        <a href="#" @click.prevent="gotoLogin">立即登录</a>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { useUserStore } from "@/store/user";
import type { LoginFormData } from "@/types/auth";



const router = useRouter();
const userStore = useUserStore();
const loginFormRef = ref<FormInstance>();

const formData = ref<LoginFormData>({
  username: "",
  password: "",
  confirmPassword: "",
  email: "",
  code: "",
});

// 账户类型
let loginMode = ref<"account" | "email">("email");
const switchLoginMode = (mode: "account" | "email") => {
  loginMode.value = mode;
};

const validateConfirmPassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请确认密码'));
  } else if (value !== formData.value.password) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
};

const main = async () => {
  try {
    console.log('1');

    let result = await userStore.getTest();
    console.log('2');

    //    let result =await testCode({})
    //    console.log('result',result);


    //    let result2 = sendSmsCode2({
    //     "email": "123@qq.com", //必填
    //     "sendType": "3", //他是一个枚举，1账户注册，3是密码找回
    //    })
    console.log('result', result);
  } catch (error) {

  }
}

setTimeout(main, 1000);

const rules = ref<FormRules<LoginFormData>>({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    {
      type: "email",
      message: "请输入有效的邮箱地址",
      trigger: ["blur", "change"],
    },
  ],
  code: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { min: 8, max: 8, message: "验证码为8位字符", trigger: "blur" },
  ],
  confirmPassword: [{ validator: validateConfirmPassword, trigger: 'blur' }],
});

const loading = ref(false);

// 发送验证码
// 60秒内只能发送一次
let sendTime = ref(60);
// 倒计时函数
const sendCountdown = () => {
  if (sendTime.value > 0) {
    sendTime.value--;
    setTimeout(sendCountdown, 1000);
  } else {
    sendTime.value = 60; // 重置倒计时
  }
};
const sendCode = async () => {
  try {
    if (!formData.value.email) {
      ElMessage.error("请输入邮箱地址");
      return;
    }
    loading.value = true;
    await userStore.sendEmailCode({
      email: formData.value.email,
      sendType: "1",
    });

    ElMessage.success("验证码已发送，请查收");
    sendCountdown();
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error("发送验证码失败");
    }
  } finally {
    loading.value = false;
  }
};

const handleSubmit = async () => {
  try {
    // 验证表单
    await loginFormRef.value?.validate();

    loading.value = true;

    await userStore.emailVerifyCode({
      email: formData.value.email,
      sendType: "1",
      verificationCode: formData.value.code,
    });

    let result = await userStore.register({
      username: formData.value.username,
      email: formData.value.email,
      password: formData.value.password,

    });
    if (result) {
      ElMessage.success("注册成功");
      router.push("/");
    } else {
      if (loginMode.value === "email") {
        ElMessage.error("邮箱登录失败，请检查邮箱或验证码");
      } else {
        ElMessage.error("用户名或密码错误");
      }
    }

  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(error.message || "注册失败");
    }
  } finally {
    loading.value = false;
  }
};

const gotoLogin = () => {
  router.push("/login");
};


</script>

<style lang="scss" scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
  background-image: url("/source/png/bg.png");
  background-repeat: no-repeat;
  background-size: cover;

  .register-box {
    width: 90%;
    max-width: 400px;
    padding: 30px;
    margin: 20px 0;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .register-header {
      text-align: center;
      margin-bottom: 20px;

      .logo {
        width: 80px;
        height: 80px;
        margin: 0 auto 15px;
        background: linear-gradient(to right, #3498db, #e2aa93);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;

        i {
          font-size: 36px;
          color: white;
        }
      }

      .register-title {
        text-align: center;
        margin-bottom: 10px;
        color: #2c3e50;
        font-size: 28px;
        font-weight: 600;
        position: relative;
        padding-bottom: 15px;

        &::after {
          content: "";
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 80px;
          height: 4px;
          background: linear-gradient(to right, #3498db, #e2aa93);
          border-radius: 2px;
        }
      }

      .register-subtitle {
        color: #7f8c8d;
        font-size: 16px;
        margin-top: 8px;
        text-align: center;
      }

    }

    .register-form {
      margin-bottom: 20px;

      .el-form-item {
        padding-top: 3px;
      }

      .code-btn {
        min-width: 60px;
        text-align: center;
      }

      .register-btn {
        margin-top: 10px;
        width: 100%;
        height: 50px;
        border-radius: 12px;
        font-size: 16px;
        font-weight: 600;
        letter-spacing: 1px;
        background: linear-gradient(to right, #3498db, #e2aa93);
        border: none;
        transition: all 0.3s ease;
        box-shadow: 0 4px 15px rgba(52, 152, 219, 0.3);

        &:hover {
          box-shadow: 0 6px 20px rgba(52, 152, 219, 0.4);
        }
      }
    }

    .login-link {
      text-align: center;
      margin-top: 20px;
      padding-top: 20px;
      border-top: 1px solid #ecf0f1;
      color: #7f8c8d;
      font-size: 15px;

      a {
        color: #3498db;
        text-decoration: none;
        font-weight: 500;
        margin-left: 5px;
      }
    }
  }
}
</style>
